
TARGET         = dkbasic
CSRC           = main.c dkstatements.c dkfunctions.c dkconstanttable.S dkinteractive.c dkterm.c dkstring.c dkexpression.c dkvariables.c dkinterpreter.c dkprogram.c dkeeprom.c lcd.c dktelly.c dkfile.c dkfile_uart.c dkfile_twi.c dkvt100.c dkevents.c dktimer.c dkfile_spi.c dkfile_eeprom.c dkfile_flash.c dkstartupbas_flash.c dkfile_ps2kbd.c scancodes.c 
ASRC           = dkstatementtable.S dkfunctiontable.S dktables.S
MCU_TARGET     = atmega2561
#MCU_TARGET     = atmega644p
#MCU_TARGET      = atxmega128a1
OPTIMIZE       = -Os -mcall-prologues
DEFS           = -DF_CPU=3686000
LIBS           = 
DEBUG          = dwarf-2
BOOTLOAD = 0x3F000
FLASHFILE = 0x20000

CC             = avr-gcc -lm
ASFLAGS        = -Wa,-adhlns=$(<:.S=.lst),-gstabs 
ALL_ASFLAGS    = -mmcu=$(MCU_TARGET) -I. -x assembler-with-cpp $(ASFLAGS)
CFLAGS         = -g$(DEBUG) -Wall $(OPTIMIZE) -mmcu=$(MCU_TARGET) $(DEFS)
LDFLAGS        = -Wl,-u,vfprintf -lprintf_flt
LDFLAGS += -Wl,--section-start=.bootloader=$(BOOTLOAD)
LDFLAGS += -Wl,--section-start=.flashfile=$(FLASHFILE)
OBJ            = $(CSRC:.c=.o) $(ASRC:.S=.o)

OBJCOPY        = avr-objcopy
OBJDUMP        = avr-objdump
SIZE           = avr-size

HEX_FLASH_FLAGS = -R .eeprom -R .fuse -R .lock -R .signature
#HEX_FLASH_FLAGS = -j .text -j .data -j .bootloader

HEX_EEPROM_FLAGS = -j .eeprom
HEX_EEPROM_FLAGS += --set-section-flags=.eeprom="alloc,load"
HEX_EEPROM_FLAGS += --change-section-lma .eeprom=0 --no-change-warnings



all: $(TARGET).elf lst text eep size

$(TARGET).elf: $(OBJ)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS)


prog: clean all
	avrdude -p $(MCU_TARGET) -c jtag2 -P usb -U flash:w:$(TARGET).hex
#	avrdude -p $(MCU_TARGET) -c jtag2 -P usb -U flash:w:$(TARGET).hex -U eeprom:w:$(TARGET).eep:r
#	avrdude -p $(MCU_TARGET) -c stk500 -P /dev/ttyUSB1 -U flash:w:$(TARGET).hex -U eeprom:w:$(TARGET).eep:r

clean:
	rm -rf *.o $(TARGET).elf *.eps *.bak *.a
	rm -rf *.lst *.map $(EXTRA_CLEAN_FILES)
	rm -rf $(TARGET).hex
	rm -rf $(TARGET).eep

size: $(TARGET).elf
#	$(SIZE) --target=$(MCU_TARGET) $(TARGET).elf
	$(SIZE) -C --mcu=$(MCU_TARGET) $(TARGET).elf

lst:  $(TARGET).lst
%.lst: %.elf
	$(OBJDUMP) -h -S $< > $@

%.o : %.S
	$(CC) -c $(ALL_ASFLAGS) $< -o $@


eep: $(TARGET).eep

%.eep: %.elf
	$(OBJCOPY) -O binary $(HEX_EEPROM_FLAGS) $< $@


text: hex
hex:  $(TARGET).hex

%.hex: %.elf
	$(OBJCOPY) -O ihex $(HEX_FLASH_FLAGS) $< $@


